import { forwardRef, useCallback, useContext, useMemo, useRef, useState } from 'react';
import { ConfigProvider, Table } from 'antd';
import '../../style.less';
import ResizableTitle from '../../preview/web/ResizableTitle';
import { TableRowSelection } from 'antd/lib/table/interface';
import { RecordType, TablePreviewProps } from '../../interfaces';
import {commonLang} from '@inbiz/utils'
import cls from 'classnames';
import {
  useColumns,
  useColumnsWidth,
  useFormatColumns,
  useInbizPrefixCls,
  useResize,
} from '../../hooks';
import { useEvents } from '@inbiz/utils';
import { InBizTableCtx } from '../../context';
import TableTop from '../../preview/web/TableTop';
import Search from '../../preview/web/Search';
import ResizeObserver from 'rc-resize-observer';
import { GlobalRegistry } from '@inbiz/core';

const TableDesigner = (props: TablePreviewProps, ref: any) => {
  const {
    prefixCls = 'table',
    rowSelection,
    emit,
    callBackEvents,
    zebraEffect,
  } = useContext(InBizTableCtx);
  const designerPrefixCls = useInbizPrefixCls(prefixCls);
  const newRowSelection: TableRowSelection<RecordType> | undefined = useMemo(() => {
    return rowSelection ? {} : undefined;
  }, [rowSelection]);
  const columns = useFormatColumns();
  const colsRef = useRef(columns);
  const [, setResizeColumn] = useState<{}>();

  const handleResize = useCallback(
    (index: number) =>
      (e: any, { size }: any) => {
        if (colsRef.current) {
          colsRef.current[index].width = size?.width;
        }
        setResizeColumn({});
      },
    [],
  );

  useResize(columns, handleResize);

  const [] = useEvents(callBackEvents, emit);
  const tableRef = useRef<HTMLDivElement>(null);

  const [tableWidth, setTableWidth] = useState<number>(document.body.clientWidth);
  const totalWidth = useColumnsWidth(columns);
  const mergedColumns = useColumns(tableWidth, totalWidth, columns);
  const scrollX = () => {
    const sum = mergedColumns.reduce((prev, next) => {
      return prev + Number(next.width ?? 100);
    }, 0);
    if (sum <= tableWidth) {
      return undefined;
    }
    return 'max-content';
  };
  const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
  return (
    <div className={cls(designerPrefixCls, 'designable-table', { zebra: zebraEffect })}>
      <InBizTableCtx.Provider value={{ ...props, isDesignable: true }}>
        <TableTop searchNode={<Search />} />
        <ConfigProvider locale={locale}>
          <ResizeObserver
            onResize={({ width }) => {
              window.requestAnimationFrame(() => {
                setTableWidth(width);
              });
            }}
          >
            <Table
              ref={tableRef}
              rowKey="id"
              scroll={{
                x: scrollX(),
              }}
              columns={mergedColumns}
              components={{
                header: {
                  cell: ResizableTitle,
                },
              }}
              size={props.size || 'small'}
              rowSelection={newRowSelection}
              title={undefined}
            />
          </ResizeObserver>
        </ConfigProvider>
      </InBizTableCtx.Provider>
    </div>
  );
};

export default forwardRef(TableDesigner);
